#define EI_ARDUINO_INTERRUPTED_PIN
#include <EnableInterrupt.h>

byte receiver_pins[4] = { 8, 9, 10, 11 };
volatile int receiver_input[4];
unsigned long timer_1, timer_2, timer_3, timer_4;

void pwmReceive();

int deadZone(int raw,int range){
  if(raw>0)
    raw = raw>range?raw:0;
  else
    raw = raw<-range?raw:0;
  return raw;
}

void setup() {
  Serial.begin(115200);
  for (int i = 0; i < 4; i++) {
    pinMode(receiver_pins[i], INPUT_PULLUP);
    enableInterrupt(receiver_pins[i], pwmReceive, CHANGE);
  }
  //开启中断
  sei();
}

void loop() {
  delay(500);
  Serial.print(deadZone(receiver_input[0] - 1500,50));
  Serial.print(":");
  Serial.print(deadZone(receiver_input[1] - 1500,50));
  Serial.print(":");
  Serial.print(deadZone(receiver_input[2] - 1500,50));
  Serial.print(":");
  Serial.print(deadZone(receiver_input[3] - 1500,50));
  Serial.print("\n");
}

/**
 * 中断函数
 */
void pwmReceive() {
  //获取当前的PIN触发的引脚
  int currPin = arduinoInterruptedPin;
  //获取当前的微秒
  unsigned long currTime = micros();

  //拿到的是当前的引脚的高低电平。 0是从高到低电平，>0 代表是从低到高电平
  int pinLevel = arduinoPinState;

  if (currPin == 8 && pinLevel > 0) {
    //为高电平
    timer_1 = currTime;
  } else if (currPin == 8 && pinLevel == 0) {
    //低电平
    receiver_input[0] = currTime - timer_1;
  }

  if (currPin == 9 && pinLevel > 0) {
    //为高电平
    timer_2 = currTime;
  } else if (currPin == 9 && pinLevel == 0) {
    //低电平
    receiver_input[1] = currTime - timer_2;
  }

  if (currPin == 10 && pinLevel > 0) {
    //为高电平
    timer_3 = currTime;
  } else if (currPin == 10 && pinLevel == 0) {
    //低电平
    receiver_input[2] = currTime - timer_3;
  }

  if (currPin == 11 && pinLevel > 0) {
    //为高电平
    timer_4 = currTime;
  } else if (currPin == 11 && pinLevel == 0) {
    //低电平
    receiver_input[3] = currTime - timer_4;
  }
}